//测试vscode工具第san次更改
define(["jquery", "text",'yfUtil','fastclick'], function ($, text,yfUtil,fastClick) {
	var fadeOutTime = 60;          //页面跳转时的渐变时间
	var yf = {
		initialize: function () {
			//设置全局变量
			yf.setGlobalVariable();
			//页面渲染
			yf.render();
			//初始化路由
			yf.initializeRoute();
			//绑定标签页切换
			yf.bindTap();
			//路由和渲染入口
			yf.judgeHash();
			//yf.bindSameTap();
			//绑定返回事件            
			//yf.bindGoBack();
			yf.setFastClick()
		},
		setFastClick:function(){
			//解决点击300毫秒延迟
			fastClick.attach(document.body);  
		},
		//设置全局变量
		setGlobalVariable: function () {
			yf.viewObj = []; //视图对象数组
			yf.temporaryObj = null;
		},
		render: function () {
			/*确保不是顶部导航*/
			var header = $('header:first');
			if (!header.hasClass('tap')) { 
			}
			/*算出view的高度*/
			var bodyHeight = $('body').height();
			var viewHeight;
			var timepHeight = bodyHeight;
			/*css('height')比height()多算出一个像素的高度*/
			var childrens = $('body').children();
			for (var i = 0; i < childrens.length; i++) {
				var item = $(childrens[i]);
				var height = parseInt(item.css('height'));
				timepHeight = timepHeight - height;
				console.log(timepHeight)
			}
			//console.log(timepHeight);
			$('.view').css('height', timepHeight + 'px');
		},
		//初始化路由
		initializeRoute: function () {
			function Router() {
				this.routes = {};
				this.currentUrl = '';
			}
			Router.prototype.route = function (path, callback) {
				this.routes[path] = callback || function () {};
			};
			Router.prototype.refresh = function () {
				this.currentUrl = location.hash.slice(1) || '/';
				//加判断，谨防报错
				if (typeof this.routes[this.currentUrl] === "function") {
					this.routes[this.currentUrl]();
				}
			}
			Router.prototype.init = function () {
				window.addEventListener('load', this.refresh.bind(this), false);
				window.addEventListener('hashchange', this.refresh.bind(this), false);
			}
			window.Router = new Router();
			window.Router.init();
		},
		judgeHash: function () {
			/*
			为"" : navigate("main")
			为main : addDivView("main")
			为其他 :  navigate("main");navigate(其他);
			 */
			var hash = location.hash;
			//如果存在路由
			if (hash !== "") {
				//监听不到路由变化，所以要直接添加div
				hash = hash.slice(1); //去掉井号
				//如果路由不为首页的时候刷新了，就先跳转到首页，再跳转到刷新的这个页面
				if (hash != "main") {
					//这里可以加一个动画遮挡
					yf.navigate("main");
					//yf.addDivView("main");
					//这里有异步
					setTimeout(function () {
						yf.navigate(hash);
					}, 0);
				} else {
					//如果路由为main，就是首页的时候刷新，就直接添加首页的div，不用改变路由
					yf.addDivView(hash);
					//这里用navigate不行,因为路由没有变化,先让他变空，再变为main用navigate就可以了
					//但是这样的话会生成两次div id="main"
					//location.hash = "";
					//yf.navigate(hash);        
				}
			} else {
				//如果路由为空，则跳转到“main”
				//yf.addDivView("main");
				yf.navigate("main");
			}
		},
		navigate: function (url, navigateArg) {
			yf.navigateType = 0;
			yf.commonNavigate(url, navigateArg);
		},
		//标签页切换，下面改变整个页面
		//与navigate的区别是一个是导航栏下面的都变，一个是导航栏和标签页下面的改变
		tapNavigate: function (url, navigateArg) {
			yf.navigateType = 1;
			yf.commonNavigate(url, navigateArg);
		},
		//公共部分
		commonNavigate: function (url, navigateArg) {
			yf.navigateArg = navigateArg;
			yf.setRoute(url);
			location.hash = url;
		},
		setRoute: function (route) {
			//设置路由
			Router.route(route, function () {
				yf.addDivView(route);
			});
		},
		addDivView: function (route) {
			if (yf.navigateType == 1) {
				var divViews = $('.body');
				for (var i = 0; i < divViews.length; i++) {
					var item = divViews[i];
					//循环一遍div，如果已经有了，则显示隐藏，并跳出代码，没有的话继续执行下面的代码，追加列表
					if ($(item).attr('id') === route) {
						divViews.hide();
						$(item).show();
						//return是结束整个函数的运行，就是整个addDivView都终止了
						return;
					}
				}
			}
			//navigate打开的页面返回的时候并非简单删除页面和obj，也会触发路由执行函数的，所以这里要判断一下
			//不然会出现两个重复的view，就像两个main
			if($(".view").find('#'+route).length!=0){
				return;
			}
			var url = "text!./" + route + '.html';
			require([url], function (loadHtml) {
				$('title').html(route);
				var loadHtml = $(loadHtml);
				loadHtml.attr('id', route); //手动增加id
				var divViews = $('.body');
				for (var i = 0; i < divViews.length; i++) {
					var item = divViews[i];
					divViews.hide();
				}
				$('.view').append(loadHtml);
				//引入相关js
				yf.addJs(route);
			});
		},
		addJs: function (route) {
			//通过require引入js
			function requireAddJs() {
				var url = route + '.js';
				require([url], function (obj2) {
					if (typeof (obj2) == "function") {
						var obj3 = new obj2();
					} else {
						var obj3 = obj2;
					}
					yf.viewObj.push(obj3);
					//获取navigateArg
					if (yf.navigateArg) {
						var navigateArg = yf.navigateArg;
						obj3.getNavigateArg = function () {
							return navigateArg;
							yf.navigateArg = null; //销毁
						}
					}
					//获取body
					var id = route;
					var body = document.getElementById(id);
					obj3.$el = $(body);
					//执行绑定
					var events = obj3.bindEvents;
					for (var i in events) {
						/*把事件都绑定到body上，这样新生成的元素才可以绑定
						$('body').on('click','#main .menuList',function(e){me.clickMenu(e);});
						用到闭包知识，百度闭包循环
						* */
						(function (arg) {
							var arr = i.split(" ");
							var eventsType = arr[0];
							var eventsElement = arr[1];
							eventsElement = "#" + id + ' ' + eventsElement;
							console.log(eventsElement);
							var eventsName = events[arg];
							$(document).on(eventsType, eventsElement, function (e) {
								obj3[eventsName](e)
							});
						})(i);
					}
					obj3.initialize();
				});
			}
			requireAddJs();
		},
		//绑定标签页切换
		bindTap: function () {
			var tapList = $('header.tap>div');
			tapList.on('click', function (e) {
				var target = $(e.currentTarget);
				tapList.removeClass('tapActive');
				target.addClass('tapActive');
				var url = target.attr('data-url');
				yf.tapNavigate(url);
				console.log("yf/bindTap");
			});
			var hash = location.hash;
			if (hash == "") {
				hash = "main"
			} else {
				hash = hash.slice(1);
			}
			//获取当前路由对应的那个标签，并点击它
			//不是点击，应该是addClass('active')
			$('header.tap div[data-url=' + hash + ']').addClass('tapActive');
		},
		bindGoBack: function () {
			var goBack = document.getElementsByClassName('goBack')[0];
			if (goBack != null) {
				goBack.addEventListener('click', function () {
					var body = $('.body');
					if (body.length === 1) {
						yf.goBack_WP();
					} else {
						yf.goBack_NVG();
					}
				});
			}
		},
		openWebPage: function (url) {
			//新开窗口，才能使用window.close()关闭，需要原生webview配合
			var isPC = yf.isPC();
			if (isPC) {
				var locationHref = window.location.href;
				if (locationHref.indexOf("homePage") > -1) {
					var routeList = [];
				} else {
					var routeList = JSON.parse(localStorage.getItem('routeList'));
				}
				routeList.push(locationHref);
				localStorage.setItem('routeList', JSON.stringify(routeList));
				$('body').fadeOut(fadeOutTime,function(){
					window.open(url, '_self');
				});
			} else {
				window.open(url);
			}
		},
		goBack_WP: function () {
			var isPC = yf.isPC();
			if (isPC) {
				//关闭当前页,必须是用js打开的才能这样关闭,但是用open(url,'_self')之后就不能用close了
				var routeList = JSON.parse(localStorage.getItem('routeList'));
				var url = routeList[routeList.length - 1];
				routeList.pop();
				localStorage.setItem('routeList', JSON.stringify(routeList));
				$('body').fadeOut(fadeOutTime,function(){
					window.open(url, '_self');
				});
			} else {
				window.close();
				//history.back();
				//不会重新刷新页面，但是会执行js
				//history.back(-1);
			}
		},
		goBack_NVG: function () {
			//改变路由
			history.back(-1);
			yf.viewObj.pop();
			$('.body:last').remove();
			$('.body:last').show();
		},
		//检测设备
		isPC: function () {
			var userAgentInfo = navigator.userAgent;
			var Agents = ["Android", "iPhone",
				"SymbianOS", "Windows Phone",
				"iPad", "iPod"
			];
			var flag = true;
			for (var v = 0; v < Agents.length; v++) {
				if (userAgentInfo.indexOf(Agents[v]) > 0) {
					flag = false;
					break;
				}
			}
			//先设定为电脑
			var flag = true;
			return flag;
		}
	}
	//将yfUtil的方法整合到yf中
	yf = $.extend({},yf,yfUtil);
	return yf;
});